package com.easpeed.user.utils

import android.content.Context
import android.content.Intent
import android.util.Log;
import com.bigyu.utils.Logger
import android.webkit.MimeTypeMap
import androidx.core.content.FileProvider
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.FileUtils
import com.easpeed.elevator.bean.LineBean
import com.easpeed.elevator.bean.RouteBean
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.File

/**
 * Created by bigyu on 2024/10/31 09:32
 * com.easpeed.user.utils
 */
object FileHelper {


    fun getPath(mContext: Context?): String {
        try {
            val path: String = mContext!!.filesDir.absolutePath
            val file = File(path + File.separator + "cache.txt")
            if (file.exists()) {
                file.delete()
            }
            FileUtils.createOrExistsFile(file.absolutePath)
            return file.absolutePath
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    fun getRouteCachePath(mContext: Context?): String {
        try {
            val cachePath = getCachePath(mContext, "route.txt")
            return cachePath
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    fun getCachePath(mContext: Context?, fileName: String): String {
        try {
            val path: String = mContext!!.filesDir.absolutePath
            val file = File(path + File.separator + fileName)
            if (file.exists()) {
                file.delete()
            }
            FileUtils.createOrExistsFile(file.absolutePath)
            return file.absolutePath
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    fun getPicturePath(mContext: Context?): String {
        try {
            val path: String = mContext!!.filesDir.absolutePath

            val file = File(path + File.separator + "img" + File.separator)
            file.mkdirs()
            Logger.e("TAG", "图片路径  ${file.absolutePath}")
            return file.absolutePath
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    fun getMimeType(file: File): String? {
        val extension = MimeTypeMap.getFileExtensionFromUrl(file.absolutePath)
        return if (extension != null) {
            MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension)
        } else null
    }


    fun shareFile(context: Context?, filePath: String?) {
        if (context == null || filePath == null) {
            return
        }
        try {
            val file = File(filePath)
            val shareIntent = Intent(Intent.ACTION_SEND)
            val mimeType = getMimeType(file) ?: "*/*"
            Logger.e("TAG", "shareFile:$mimeType ")
            val provider = "${AppUtils.getAppPackageName()}.fileProvider"
            val fileUri = FileProvider.getUriForFile(context, provider, file)
//                shareIntent.setDataAndType(fileUri, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            shareIntent.setDataAndType(fileUri, mimeType);
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            shareIntent.putExtra(Intent.EXTRA_STREAM, fileUri)
            context.startActivity(Intent.createChooser(shareIntent, "share"))
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun readLineData(mContext: Context?): ArrayList<LineBean> {
        val lineList = ArrayList<LineBean>()
        try {
            val path: String = mContext!!.filesDir.absolutePath
            val file = File(path + File.separator + "line.json")
            val fileTemp = File(path + File.separator + "line_temp.json")
            if (file.exists()) {
                if (fileTemp.exists()) {
                    fileTemp.delete()
                }
                val copySuccess = FileUtils.copyFile(file, fileTemp)
                Logger.e("TAG", "备份文件成功：$copySuccess")
            }
            val success = FileUtils.createOrExistsFile(file)
            //            success = FileUtils.writeFileFromString(file, "111111", false);
            val file2String = FileUtils.readFile2String(file, "utf-8")
            Logger.e("TAG", "initData: $file2String")

            val gson = Gson()
            val type = object : TypeToken<List<LineBean?>?>() {
            }.type
            val list = gson.fromJson<Any>(file2String, type) as List<LineBean>
            lineList.addAll(list)
        } catch (e: Exception) {
//            e.printStackTrace()
        }
        return lineList
    }

    fun readRouteData(mContext: Context?): ArrayList<RouteBean> {
        val lineList = ArrayList<RouteBean>()
        try {
            val path: String = mContext!!.filesDir.absolutePath
            val file = File(path + File.separator + "route.json")
            val fileTemp = File(path + File.separator + "route_temp.json")
            if (file.exists()) {
                if (fileTemp.exists()) {
                    fileTemp.delete()
                }
                val copySuccess = FileUtils.copyFile(file, fileTemp)
                Logger.e("TAG", "备份文件成功：$copySuccess")
            }
            val success = FileUtils.createOrExistsFile(file)
            //            success = FileUtils.writeFileFromString(file, "111111", false);
            val file2String = FileUtils.readFile2String(file, "utf-8")
            Logger.e("TAG", "initData: $file2String")

            val gson = Gson()
            val type = object : TypeToken<List<RouteBean?>?>() {
            }.type
            val list = gson.fromJson<Any>(file2String, type) as List<RouteBean>
            lineList.addAll(list)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return lineList
    }

    fun saveRouteData(mcContext: Context?, lineList: ArrayList<RouteBean>) {
        try {
            val gson = Gson()
            val json = gson.toJson(lineList)
            val path: String = mcContext!!.filesDir.absolutePath
            val file = File(path + File.separator + "route.json")
            val fileTemp = File(path + File.separator + "route_temp.json")
            if (file.exists()) {
                if (fileTemp.exists()) {
                    fileTemp.delete()
                }
                val copySuccess = FileUtils.copyFile(file, fileTemp)
                Logger.e("TAG", "备份文件成功：$copySuccess")
            }
            FileUtils.writeFileFromString(file, json, false)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    fun saveLineData(mcContext: Context?, lineList: ArrayList<LineBean>) {
        try {
            val gson = Gson()
            val json = gson.toJson(lineList)
            val path: String = mcContext!!.getFilesDir().getAbsolutePath()
            val file = File(path + File.separator + "line.json")
            val fileTemp = File(path + File.separator + "line_temp.json")
            if (file.exists()) {
                if (fileTemp.exists()) {
                    fileTemp.delete()
                }
                val copySuccess = FileUtils.copyFile(file, fileTemp)
                Logger.e("TAG", "备份文件成功：$copySuccess")
            }
            FileUtils.writeFileFromString(file, json, false)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }
}